﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityBinder.Interface;

namespace EntityBinder.Json
{
	class JsonElementWriter : IElementWriter
	{
		class Property
		{
			public bool InArray { get; set; }

			public Property()
			{
				InArray = false;
			}
		}

		private Newtonsoft.Json.JsonWriter m_writer = null;

		private Stack<Property> m_properties = new Stack<Property>();
		private Property CurrentProperty
		{
			get 
			{
 				if(m_properties.Count > 0)
					return m_properties.Peek();
				return new Property();
			}
		}

		public JsonElementWriter(Newtonsoft.Json.JsonWriter _writer)
		{
			if(_writer == null)
			{
				throw new EntityBinderException("JsonElementWriter", "<ctor>", "Can not create an JsonElementWriter without any Writer");
			}
			m_writer = _writer;
		}

		public void WriteObjectStart(string _containerName)
		{
			WriteProperty(_containerName);
			m_writer.WriteStartObject();

			Push(false);
		}

		public void WriteObjectEnd()
		{
			m_writer.WriteEndObject();

			Pop();
		}

		public void WriteArrayStart(string _arrayName)
		{
			WriteProperty(_arrayName);
			m_writer.WriteStartArray();

			Push(true);
		}

		public void WriteArrayEnd()
		{
			m_writer.WriteEndArray();

			Pop();
		}

		public void WriteElementStart(string _elementName)
		{
			WriteProperty(_elementName);

			Push(false);
		}

		public void WriteElementEnd()
		{
			Pop();
		}

		public void WriteElementValue(string _value)
		{
			m_writer.WriteValue(_value);
		}

		private void Push(bool _inArray)
		{
			m_properties.Push(new Property() { InArray = _inArray });
		}

		private void Pop()
		{
			m_properties.Pop();
		}

		private void WriteProperty(string _name)
		{
			if (!CurrentProperty.InArray)
			{
				m_writer.WritePropertyName(_name);
			}
		}
	}
}
